package com.google.springfacestools.validation;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;

public class ValidationMessages {

	@Autowired
	private FacesContext facesContext;
	private boolean hasErrors = false;
	
	public boolean hasErrors() {
		return hasErrors;
	}
	
	public void addErrors(String beanName, Errors errors) {
		if(errors.hasErrors()) {
			for(Object item: errors.getAllErrors()) {
				ObjectError error = (ObjectError) item;
				facesContext.addMessage(error.getObjectName(), new FacesMessage(error.getCode()));
			}
		}
		hasErrors = true;
	}
	
	public void addError(Throwable e) {
		facesContext.addMessage("error", new FacesMessage(e.getMessage()));
		hasErrors = true;
	}
	
	public void addMessage(String message) {
		facesContext.addMessage("message", new FacesMessage(message));
	}
	
}